#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/10/19 15:11
# file: user.py
# author: lotus163
from typing import Optional

from fastapi import APIRouter, Depends

from ...core.datascope import DataScope
from ...core.deps import UserDepends, get_user_depends
from ...core.result import Result, result_success, ResultData
from ...crud import DeptDao
from ...schemas import SysDeptAdd, SysDeptSch
from ...utils.form_util import get_form_dict

router = APIRouter(prefix="/dept", tags=["部门"])


@router.put("", response_model=Result, summary='修改部门')
async def update_dept(form: SysDeptSch, user_depends: UserDepends = Depends(get_user_depends)):
    # 数据过滤,失败则抛出异常
    if not user_depends.login_user.user.admin:
        DataScope(user_depends.login_user.data_scope.roles_depts_ids).has_sope(form.deptId)
    # 添加创建者
    form.updateBy = user_depends.login_user.user.userName
    dept_db = await DeptDao.get_db_or_none(deptId=form.deptId)
    await DeptDao.update_sch(obj=dept_db, **form.dict(exclude_none=True))
    return result_success()


@router.post("", response_model=Result, summary='新增部门')
async def add_dept(form: SysDeptAdd, user_depends: UserDepends = Depends(get_user_depends)):
    # 是否有父部门的权限
    if not user_depends.login_user.user.admin:
        DataScope(user_depends.login_user.data_scope.roles_depts_ids).has_sope(form.parentId)
    form.createBy = user_depends.login_user.user.userName
    await DeptDao.add_sch(**form.dict(exclude_none=True))
    return result_success()


@router.get("/list", response_model=ResultData, summary='获取部门列表')
async def get_depts_list(deptName: Optional[str] = None,
                         status: Optional[str] = None,
                         user_depends: UserDepends = Depends(get_user_depends)):
    # 时间
    start, end = user_depends.request_service.get_params_time()
    # 准备查询的参数
    form_dict = get_form_dict(form=SysDeptAdd(deptName=deptName, status=status),
                              start=start,end=end,time_range="createTime__range")
    # 数据权限
    if not user_depends.login_user.user.admin:
        form_dict["deptId__in"] = user_depends.login_user.data_scope.roles_depts_ids
    # 查询
    return result_success(data=await DeptDao.get_list_sch(**form_dict))


@router.get("/list/exclude/{deptId}", response_model=ResultData, summary='查询部门列表（排除节点）')
async def get_depts_list_exclude_child(deptId: int, user_depends: UserDepends = Depends(get_user_depends)):
    roles_depts_ids = user_depends.login_user.data_scope.roles_depts_ids
    if deptId in roles_depts_ids:
        roles_depts_ids.remove(deptId)
    depts_sch = await DeptDao.get_list_sch(deptId__in=roles_depts_ids)
    return result_success(data=depts_sch)


@router.get("/{deptId}", response_model=ResultData, summary='根据id获取部门信息')
async def get_dept_info(deptId: int, user_depends: UserDepends = Depends(get_user_depends)):
    # 数据权限
    if not user_depends.login_user.user.admin:
        DataScope(user_depends.login_user.data_scope.roles_depts_ids).has_sope(deptId)
    dept_sch = await DeptDao.get_sch_or_none(deptId=deptId)
    return result_success(data=dept_sch)


@router.delete("/{deptId}", response_model=Result, summary='根据id删除部门')
async def remove_dept(deptId: int, user_depends: UserDepends = Depends(get_user_depends)):
    # 数据权限
    if not user_depends.login_user.user.admin:
        DataScope(user_depends.login_user.data_scope.roles_depts_ids).has_sope(deptId)
    await DeptDao.delete_db(deptId=deptId)
    return result_success()
